<template>
  <div class="project-flight-area-wrapper height-100 text-white">
    <div class="px-3 pt-2 pb-3 flex justify-between items-center">
      <h3 class="text-white text-xl">模型库</h3>
      <el-button type="primary" @click="handleOpenModel">
        <FolderUp />
        上传模型
      </el-button>
      <el-dialog v-model="isPopupModel" title="上传模型" width="600" v-if="isPopupModel">
        <UploadModel :onSuccess="onSuccess" :info="modelInfo"></UploadModel>
      </el-dialog>
    </div>
    <div class="border border-gray-300"></div>
    <div class="">
      <template v-for="item in models" :key="item.id">
        <div class="border m-2 p-2 px-4">
          <div class="flex items-center justify-between gap-4">
            <el-checkbox :disabled="!item.complete_status" v-model="item.check_status" @change="handleCheck(item)" />
            <div class="overflow-hidden w-36 whitespace-nowrap relative" v-auto-scroll>
              <span
                v-if="!item.isEditing"
                class="inline-block w-full cursor-pointer"
                @click="handleGoToModel(item)"
                @dblclick="handleEditClick(item)"
                >{{ item.model_name }}</span
              >
              <input
                v-else
                v-model="item.model_name"
                type="text"
                class="w-full px-1 border-b outline-none"
                @keyup.enter="handleInputBlur(item)"
                v-focus
              />
            </div>

            <el-button type="text" @click="handleDelete(item)">
              <CircleX class="cursor-pointer" />
            </el-button>
          </div>
          <div class="flex items-center justify-between gap-4">
            <span>状态:</span>
            <span class="text-xs flex-1">{{ item.complete_status ? '已完成' : '未完成' }}</span>
            <div v-if="!item.complete_status">
              <el-tag @click="handleCheckResume(item)" type="primary" class="cursor-pointer">上传</el-tag>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { CircleX, FolderUp } from 'lucide-vue-next'
import { getModelsApi, deleteModelApi, editModelApi, checkUploadProgressApi } from '@/api/bigfileupload'
import { message } from 'ant-design-vue'
import useGMapManage from '@/hooks/use-g-map'
import { ELocalStorageKey } from '@/types'
import { sessionStorage } from '@/utils/storage'
import { IModel } from '@/types/model'
import UseUpdate from '@/hooks/use-update'

const workspaceId: string = sessionStorage.get(ELocalStorageKey.WorkspaceId) || ''
const isPopupModel = ref(false)

const models = ref<IModel[]>([])
const editingValue = ref('')
// 在methods中添加
const handleEditClick = (item: IModel) => {
  item.isEditing = true
  // 保存原始值用于可能的回滚
  editingValue.value = item.model_name
}
const handleGoToModel = (item: IModel) => {
  if (item.check_status) {
    useGMapManage.flyToModel(item.upload_id)
    console.log('跳转到模型上面', item)
  }
}
const checks = ref<any[]>([])
const modelInfo = ref<IModel | null>(null)
// 断点续传
const handleCheckResume = async (item: IModel) => {
  modelInfo.value = { ...item, isDisabled: true }
  isPopupModel.value = true
}
const handleInputBlur = async (item: IModel) => {
  item.isEditing = false
  // 这里可以添加保存逻辑，比如：
  if (editingValue.value !== item.model_name) {
    const params = {
      uploadId: item.upload_id,
      modelName: item.model_name
    }
    const { code } = await editModelApi(params)
    if (code === 1) {
      message.success('修改模型名称成功')
    }
  }
}
const getModels = async () => {
  const params = { page: 1, page_size: 10, workspaceId, key: '' }
  const { code, data } = await getModelsApi(params)
  if (code !== 1) {
    return message.error('获取模型列表失败')
  }

  data.list?.forEach((item) => {
    if (item.check_status) {
      useGMapManage.addModel(item.tileset_url, item.upload_id)
      console.log('渲染模型', item)
    }
    // console.log(item, '获取模型数据列表')
  })
  models.value = data.list.map((item) => ({ ...item, isEditing: false }))
}
const handleCheck = async (item: IModel) => {
  const params = {
    uploadId: item.upload_id,
    checkStatus: item.check_status
  }
  const { code } = await editModelApi(params)
  if (code === 1) {
    message.success('修改模型状态成功')
    console.log('修改模型状态成功', item, params)
    if (!item.check_status) {
      useGMapManage.removeModelById(item.upload_id)
      console.log('移除模型', item)
    } else {
      useGMapManage.addModel(item.tileset_url, item.upload_id)
      console.log('渲染模型', item)
    }
    // await getModels()
  }
}
const handleOpenModel = () => {
  isPopupModel.value = true
  modelInfo.value = null
}
onMounted(async () => {
  const viewer = useGMapManage.getViewer()
  console.log('model组件', viewer)
  await getModels()
})
const onSuccess = async () => {
  isPopupModel.value = false
  await getModels()
}
const handleDelete = async (item: IModel) => {
  const { code } = await deleteModelApi(item.upload_id)
  if (code !== 1) {
    message.error('删除模型失败')
  }
  message.success('删除模型成功')
  await getModels()
}
onUnmounted(() => {
  // 卸载所有的模型
  useGMapManage.getAllModels().forEach((item) => {
    console.log('卸载模型', item)
    useGMapManage.removeModelById(item.customId!)
  })
})
</script>

<style lang="scss" scoped>
.custom-input {
  flex-grow: 1;
  margin: 0 8px;
}

.delete-icon {
  cursor: pointer;
}
</style>
